/*************************************************************************
    > File Name    : Thread.cc
    > Author       : LiuLei
    > Mail         : 2261459486@qq.com 
    > Created Time : 2022年11月24日 星期四 21时36分46秒
 ************************************************************************/

#include "../../include/server/Thread.h"
#include <stdio.h>

Thread::Thread(const ThreadCallback &cb, int thIndex)
: _thIndex(thIndex)
, _thId(0)
, _isRunning(false)
, _cb(std::move(cb))
{

}

Thread::Thread(ThreadCallback &&cb, int thIndex)
: _thIndex(thIndex)
, _thId(0)
, _isRunning(false)
, _cb(std::move(cb))
{

}

Thread::~Thread()
{
    if(_isRunning)
    {
        int ret = ::pthread_detach(_thId);
        if(ret)
        {
            ::perror("pthread_detach in Thread::~Thread()");
        }
    }
}

void Thread::start()
{
    int ret = ::pthread_create(&_thId, nullptr, threadFunc, this);
    if(ret)
    {
        ::perror("pthread_create in Thread::start()");
    }
    _isRunning = true;
}

void Thread::stop()
{
    if(_isRunning)
    {
        int ret = ::pthread_join(_thId, nullptr);
        if(ret)
        {
            ::perror("pthread_join in Thread::stop()");
            return ;
        }
    }

    _isRunning = false;
}

void *Thread::threadFunc(void *arg)
{
    Thread *pThread = static_cast<Thread *>(arg);
    if(pThread)
    {
        pThread->_cb();
    }
    ::pthread_exit(nullptr);
}
